/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.system.service.ISysDictDataService;
import com.comac.ins.system.service.impl.SysDictDataServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class ParseBDFUtils {
    public static final String TEMP_DIR = System.getProperty("java.io.tmpdir");

    public static Map<String, List<Map<String, Object>>> parseMaterialBDF(Path importFilePath) {
        // 调用pyNastran解析
        try {
            String formattedPath = "\"" + importFilePath.toString().replace("\\", "/") + "\"";
            log.info("传递给Python的路径: {}", formattedPath);
            return PythonExecute.excute("read_materials",formattedPath);
        } catch (Exception e) {
            // 如果失败，删除文件
            try {
                Files.deleteIfExists(importFilePath);
                log.info("上传文件已删除：{}", importFilePath);
            } catch (Exception e2) {
                log.warn("上传文件删除失败：{}", importFilePath, e2);
                throw new BaseException("上传文件删除失败：" + importFilePath);
            }
            log.error("bdf文件解析失败：", e);
            throw new RuntimeException("bdf文件解析失败：" + e);
        }
    }

    public static Path saveImportFile(String directoryPath, MultipartFile multipartFile) {
        // 检查目录是否存在
        if (directoryPath == null || directoryPath.trim().isEmpty()) {
            throw new IllegalArgumentException("目录路径不能为空或非法");
        }
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            // 尝试创建目录
            if (!directory.mkdirs()) {
                throw new RuntimeException("目标目录无法创建: " + directoryPath);
            } else {
                if (!directory.canWrite()) {
                    throw new RuntimeException("目标目录存在但不可写: " + directoryPath);
                }
            }
        }
        // 安全处理文件名, 为文件生成唯一名称，防止重复覆盖
        String uniqueFilename = processFileName(multipartFile.getOriginalFilename());

        // 构造目标文件路径
        File destinationFile = new File(directory, uniqueFilename);
        try {
            // 将 MultipartFile 转存为目标文件
            multipartFile.transferTo(destinationFile);
            log.info("文件已保存: {}", destinationFile.getAbsolutePath());
        } catch (IOException e) {
            log.error("文件保存失败", e);
            throw new RuntimeException("文件保存失败" + e);
        }
        return destinationFile.toPath();
    }

    private static String processFileName(String originalFilename) {
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        // 提取文件扩展名
        String extension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex >= 0) {
            extension = originalFilename.substring(lastDotIndex); // 包含 "."
            originalFilename = originalFilename.substring(0, lastDotIndex);
        }
        // 去除非法字符，保留基本字符、数字和部分符号
        String sanitizedFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_");
        // 添加时间戳和 UUID，避免重复
        String uniqueId = UUID.randomUUID().toString().replace("-", "").substring(0, 8); // 保留前8位
        return sanitizedFilename + "_" + uniqueId + extension;
    }
}
